package com.jahe.learn.netty4.customcodec;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * @author: jahe.lai
 * @create: 2020-01-09 12:15
 */
public class LongCodecClient {
    private static Logger logger = LoggerFactory.getLogger(LongCodecClient.class);

    public static void main(String[] args) throws Exception {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup(2);
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //HTTP编解码器
                            pipeline.addLast("long-decoder", new LongMessageDecoder())
                                    .addLast("long-encoder", new LongMessageEncoder())
                                    .addLast("long-handler", new MyLongMessageHandler());
                        }
                    });

            InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8899);
            ChannelFuture channelFuture = bootstrap.connect(address).sync();
            logger.warn("Client started {}", address);
            // 触发消息交互。
            channelFuture.channel().writeAndFlush(111111111111111L);
            // 阻塞并监听关闭信号 （在收到 CloseWebSocketFrame 时，退出监听， 进而执行finally块代码。）
            channelFuture.channel().closeFuture().sync();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
